package com.funsport.controller.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.funsport.common.Result;
import com.funsport.dto.request.WebLoginRequest;
import com.funsport.dto.response.LoginResponse;
import com.funsport.entity.Role;
import com.funsport.entity.User;
import com.funsport.security.JwtTokenProvider;
import com.funsport.service.IUserService;
import com.funsport.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Tag(name = "Web管理端认证", description = "Web管理端认证相关接口")
@RestController
@RequestMapping("/web/auth")
@RequiredArgsConstructor
public class WebAuthController {

    private final IUserService userService;
    private final RoleService roleService;
    private final JwtTokenProvider jwtTokenProvider;
    private final PasswordEncoder passwordEncoder;

    @Operation(summary = "Web管理后台登录")
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody WebLoginRequest request) {
        log.info("Web登录请求: username={}", request.getUsername());

        // 支持多种方式登录：手机号、邮箱、昵称
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .and(wrapper -> wrapper
                        .eq(User::getPhone, request.getUsername())
                        .or()
                        .eq(User::getEmail, request.getUsername())
                        .or()
                        .eq(User::getNickname, request.getUsername()))
                .in(User::getRole, "admin", "venue_manager"));

        if (user == null) {
            log.warn("用户不存在: username={}", request.getUsername());
            return Result.error(401, "用户名或密码错误");
        }

        if (user.getPasswordHash() == null) {
            log.warn("用户未设置密码: userId={}", user.getId());
            return Result.error(401, "用户未设置密码，请联系管理员");
        }

        if (!passwordEncoder.matches(request.getPassword(), user.getPasswordHash())) {
            log.warn("密码错误: userId={}", user.getId());
            return Result.error(401, "用户名或密码错误");
        }

        // 获取用户的角色列表
        List<Role> roles = roleService.getRolesByUserId(user.getId());
        List<String> roleCodes = roles.stream()
                .map(Role::getCode)
                .collect(Collectors.toList());

        // 如果没有分配角色，使用用户表中的role字段作为默认角色
        if (roleCodes.isEmpty() && user.getRole() != null) {
            String defaultRole = user.getRole().getValue().toUpperCase();
            if ("ADMIN".equals(defaultRole)) {
                roleCodes.add("ADMIN");
            } else if ("VENUE_MANAGER".equals(defaultRole)) {
                roleCodes.add("VENUE_MANAGER");
            }
            log.info("用户未分配角色，使用默认角色: {}", defaultRole);
        }

        String token = jwtTokenProvider.generateToken(user.getId(), user.getRole().getValue());
        LoginResponse response = new LoginResponse(token, user.getId(), 
                user.getRole().getValue(), user.getNickname(), user.getAvatar());
        
        // 设置角色列表
        response.setRoles(roleCodes);

        log.info("Web登录成功: userId={}, roles={}", user.getId(), roleCodes);
        return Result.success(response);
    }
}
